var express = require('express');
var router = express.Router();

const md5 = require('md5')

const moment = require('moment')
const AuthModel = require('../../models/AuthModel')

const { JWT_SECRET } = require('../../config/config')

const jwt = require('jsonwebtoken')


router.post('/login', function (req, res, next) {
  const { username, password } = req.body
  AuthModel.findOne({ username, password: md5(password) }, (err, data) => {
    if (err) {
      res.json({
        code: '1002',
        msg: '登录失败~~',
        data: null
      });
      return
    }
    if (data) {
      // Ensure session object exists before setting properties

      let token = jwt.sign({
        username: data.username,
        _id: data._id
      }, JWT_SECRET, { expiresIn: '1h' })

      res.json({
        code: '0000',
        msg: '登录成功',
        data: token
      })
    } else {
      res.json({
        code: '1002',
        msg: '用户名或密码错误~~',
        data: null
      });
    }
  })
  
})




module.exports = router;
